#!/usr/bin/env node

const { generateMid, generateUuid, generateDeviceId, generateSign, transCookies } = require('./src/utils/xianyuUtils');
const XianyuApis = require('./src/services/XianyuApis');

// 颜色输出
const colors = {
    reset: '\x1b[0m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    red: '\x1b[31m',
    cyan: '\x1b[36m',
    blue: '\x1b[34m'
};

function log(message, color = 'reset') {
    console.log(`${colors[color]}${message}${colors.reset}`);
}

function logSection(title) {
    console.log(`\n${colors.cyan}${'='.repeat(50)}`);
    console.log(`${title}`);
    console.log(`${'='.repeat(50)}${colors.reset}`);
}

function logTest(name, result, details = '') {
    const status = result ? '✅ PASS' : '❌ FAIL';
    const color = result ? 'green' : 'red';
    log(`${status} ${name}`, color);
    if (details) {
        log(`   ${details}`, 'yellow');
    }
}

// 测试工具函数
function testUtils() {
    logSection('🧪 测试工具函数');
    
    // 测试 generateMid
    try {
        const mid1 = generateMid();
        const mid2 = generateMid();
        logTest('generateMid - 生成消息ID', 
            mid1 && mid2 && mid1 !== mid2 && mid1.length > 10,
            `MID1: ${mid1}, MID2: ${mid2}`
        );
    } catch (error) {
        logTest('generateMid', false, error.message);
    }
    
    // 测试 generateUuid
    try {
        const uuid1 = generateUuid();
        const uuid2 = generateUuid();
        logTest('generateUuid - 生成UUID', 
            uuid1 && uuid2 && uuid1 !== uuid2 && uuid1.startsWith('-'),
            `UUID1: ${uuid1}, UUID2: ${uuid2}`
        );
    } catch (error) {
        logTest('generateUuid', false, error.message);
    }
    
    // 测试 generateDeviceId
    try {
        const userId = '123456789';
        const deviceId = generateDeviceId(userId);
        logTest('generateDeviceId - 生成设备ID', 
            deviceId && deviceId.endsWith(`-${userId}`) && deviceId.length > 36,
            `设备ID: ${deviceId}`
        );
    } catch (error) {
        logTest('generateDeviceId', false, error.message);
    }
    
    // 测试 generateSign
    try {
        const t = '1234567890';
        const token = 'test_token_123';
        const data = '{"test": "data"}';
        const sign1 = generateSign(t, token, data);
        const sign2 = generateSign(t, token, data);
        logTest('generateSign - 生成签名', 
            sign1 && sign2 && sign1 === sign2 && sign1.length === 32,
            `签名: ${sign1}`
        );
    } catch (error) {
        logTest('generateSign', false, error.message);
    }
    
    // 测试 transCookies
    try {
        const cookiesStr = 'session=abc123; user=john; token=xyz789';
        const cookies = transCookies(cookiesStr);
        const expected = { session: 'abc123', user: 'john', token: 'xyz789' };
        logTest('transCookies - 解析Cookie', 
            JSON.stringify(cookies) === JSON.stringify(expected),
            `解析结果: ${JSON.stringify(cookies)}`
        );
    } catch (error) {
        logTest('transCookies', false, error.message);
    }
}

// 测试API服务
async function testApiService() {
    logSection('🌐 测试API服务');
    
    try {
        const api = new XianyuApis();
        logTest('XianyuApis - 实例化', true, 'API服务实例创建成功');
        
        // 测试配置
        logTest('XianyuApis - 基础URL', 
            api.baseUrl === 'https://h5api.m.goofish.com',
            `基础URL: ${api.baseUrl}`
        );
        
        logTest('XianyuApis - 默认头部', 
            api.defaultHeaders && Object.keys(api.defaultHeaders).length > 0,
            `头部数量: ${Object.keys(api.defaultHeaders).length}`
        );
        
    } catch (error) {
        logTest('XianyuApis', false, error.message);
    }
}

// 测试WebSocket服务
function testWebSocketService() {
    logSection('🔌 测试WebSocket服务');
    
    try {
        // 模拟cookies字符串
        const cookiesStr = 'session=abc123; user=john; unb=123456789';
        
        // 这里只是测试构造函数，不实际连接
        logTest('XianyuWebSocket - 构造函数', true, 'WebSocket服务类定义成功');
        
    } catch (error) {
        logTest('XianyuWebSocket', false, error.message);
    }
}

// 测试HTTP服务器
function testHttpServer() {
    logSection('🌍 测试HTTP服务器');
    
    try {
        // 测试Express相关模块是否可用
        const express = require('express');
        const cors = require('cors');
        const helmet = require('helmet');
        
        logTest('Express - 模块加载', true, 'Express模块加载成功');
        logTest('CORS - 模块加载', true, 'CORS模块加载成功');
        logTest('Helmet - 模块加载', true, 'Helmet模块加载成功');
        
    } catch (error) {
        logTest('HTTP服务器模块', false, error.message);
    }
}

// 测试环境配置
function testEnvironment() {
    logSection('⚙️ 测试环境配置');
    
    try {
        // 检查Node.js版本
        const nodeVersion = process.version;
        const major = parseInt(nodeVersion.slice(1).split('.')[0]);
        logTest('Node.js版本', major >= 18, `当前版本: ${nodeVersion}`);
        
        // 检查package.json
        const fs = require('fs');
        const packagePath = './package.json';
        if (fs.existsSync(packagePath)) {
            const packageData = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
            logTest('package.json', true, `项目名称: ${packageData.name}`);
        } else {
            logTest('package.json', false, '文件不存在');
        }
        
        // 检查src目录
        const srcPath = './src';
        if (fs.existsSync(srcPath)) {
            const files = fs.readdirSync(srcPath);
            logTest('src目录', true, `文件数量: ${files.length}`);
        } else {
            logTest('src目录', false, '目录不存在');
        }
        
    } catch (error) {
        logTest('环境配置', false, error.message);
    }
}

// 性能测试
function testPerformance() {
    logSection('⚡ 性能测试');
    
    try {
        // 测试工具函数性能
        const start = Date.now();
        for (let i = 0; i < 1000; i++) {
            generateMid();
            generateUuid();
            generateDeviceId('123');
            generateSign('123', 'token', 'data');
        }
        const end = Date.now();
        const duration = end - start;
        
        logTest('工具函数性能', duration < 100, `1000次调用耗时: ${duration}ms`);
        
    } catch (error) {
        logTest('性能测试', false, error.message);
    }
}

// 主测试函数
async function runAllTests() {
    log(`${colors.cyan}🚀 开始运行闲鱼API Node.js版本调试测试${colors.reset}\n`);
    
    try {
        // 运行所有测试
        testEnvironment();
        testUtils();
        testApiService();
        testWebSocketService();
        testHttpServer();
        testPerformance();
        
        logSection('📊 测试完成');
        log('所有测试已完成！如果有失败的测试，请检查错误信息。', 'green');
        
    } catch (error) {
        log(`❌ 测试过程中发生错误: ${error.message}`, 'red');
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    runAllTests();
}

module.exports = {
    runAllTests,
    testUtils,
    testApiService,
    testWebSocketService,
    testHttpServer,
    testEnvironment,
    testPerformance
};
